import {Component} from '@angular/core';
import {ViewController, NavController, NavParams, ToastController, LoadingController,AlertController} from 'ionic-angular';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';
import {StorageService} from "../../providers/StorageService";

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';

import {UserService} from "../../providers/UserService";


import {TabsPage} from '../tabs/tabs';
import {STATUS_FAIL} from "../../providers/Constants";
import {JiGuanService} from "../../providers/JiGuanService";
import {BaseUI} from "../../common/baseui";
import {JmessageChenyu} from "jmessage-chenyu";


@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class Login extends BaseUI{
  loginForm: FormGroup;
  phone: any;
  password: any;
  getPhone: any;//接收注册界面的手机号
  getPassword: any;

  constructor(public navCtrl: NavController,
              public viewCtrl: ViewController,
              private formBuilder: FormBuilder,
              public loadingCtrl: LoadingController,
              public toastCtrl: ToastController,
              private userService: UserService,
              private storageService: StorageService,
              public navParams: NavParams,
              private jmessageChenyu:JmessageChenyu,
              private jiGuanService: JiGuanService,
              private alertCtrl:AlertController) {
    super();
    this.loginForm = formBuilder.group({
      phone: ['', Validators.compose([Validators.minLength(4), Validators.required,])],
      password: ['', Validators.compose([Validators.required])]
    })
    this.phone = this.loginForm.controls['phone'];
    this.password = this.loginForm.controls['password'];

    //接收手机号、密码
    this.getPhone = navParams.get('phone');
    this.getPassword = this.navParams.get('password');


  }


  ionViewDidLoad() {
    // console.log('ionViewDidLoad Login');
    console.log("page:" + this.navParams.get("page"));
  }

  //登陆
  login(value) {
    let loader = this.loadingCtrl.create({
      content: "正在登陆...",
    });
    loader.present();
    setTimeout(() => {
      this.userService.login(value).then(res => {
        if (res["status"] == STATUS_FAIL) {   //登录失败
          this.toastCtrl.create({message: res["msg"], duration: 4500}).present();
          loader.dismiss();
          return;
        }
        this.jiGuanService.login(value.phone, value.password).then(() => {//登录极光平台(成功)
          this.ClickMessageNotificationListener();//监听消息单击事件
          this.addLoginStateChangedListener();
          loader.dismiss();
          if (this.navParams.get("page") == "SignOrlogin" || this.navParams.get("page") == "SignPage") { //判断进入登录的入口
            this.navCtrl.setRoot(TabsPage);
          } else {
            this.viewCtrl.dismiss();
          }
          this.storageService.write('UserInfo', res["data"]);
        }).catch((error)=>{
          loader.dismiss();
          super.showToast(this.toastCtrl,error.description,'bottom');
        });

      });
    }, 2000);



  };

  dismiss() {
    this.viewCtrl.dismiss();
  }

  //监听消息收到时的点击事件(点击消息进入聊天页面)
  ClickMessageNotificationListener(){
    this.jmessageChenyu.addClickMessageNotificationListener((msg)=>{
      this.userService.selectUserByPhone(msg.from.nickname).subscribe(user=>{
        this.navCtrl.push("ChatdetailPage",{chatUserNickName:user['nickname'],
          chatUserFace:user['userFace'],
          chatUserPhone:msg.from.username,
          chatUserId:user['id']});
      })
    });
  }

  addLoginStateChangedListener(){
    this.jmessageChenyu.addLoginStateChangedListener((event)=>{
      this.storageService.remove('UserInfo');//清除本地用户信息
      if(event.type=='user_logout'){
        let confirm = this.alertCtrl.create({
          message: '该账户已在别处登录,是否重新登录?',
          buttons: [
            {
              text: '取消',
              handler: () => {
                // console.log('Disagree clicked');
              }
            },
            {
              text: '确定',
              handler: () => {
                this.navCtrl.push(Login,{page:'Login'});
              }
            }
          ]
        });
        confirm.present();
      }
    });
  }
}
